package mamikeji.liaowa.ui.activity.notice;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import mamikeji.liaowa.R;
import mamikeji.liaowa.bean.NoticeCommentBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.ui.activity.circle.CircleDetailsActivity;
import mamikeji.liaowa.ui.adapter.NoticeCommentAdapter;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;
import mamikeji.liaowa.widget.pulltorefresh.PullToRefreshBase;
import mamikeji.liaowa.widget.pulltorefresh.PullToRefreshListView;
import mamikeji.liaowa.widget.refreshView.PtrlDownRefreshFrameLayout;

public class Notice_CommentActivity extends BaseActivity {
    @BindView(R.id.iv_header_left)
    ImageView ivHeaderLeft;
    @BindView(R.id.iv_header_right)
    ImageView ivHeaderRight;
    @BindView(R.id.tv_header_title)
    TextView tvHeaderTitle;
    @BindView(R.id.iv_header_title)
    ImageView ivHeaderTitle;
    @BindView(R.id.rv_header_right)
    TextView rvHeaderRight;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.pullToRefreshListView)
    PullToRefreshListView pullToRefreshListView;
    @BindView(R.id.ptrlDownRefreshFrameLayout)
    PtrlDownRefreshFrameLayout ptrlDownRefreshFrameLayout;
    @BindView(R.id.multiStateView_Notice_Comment)
    MultiStateView multiStateView;
    private int pageIndex = 1;
    private int pageSize = 10;
    private List<NoticeCommentBean.DataBean> lists = new ArrayList<>();
    private NoticeCommentAdapter adapter;
    private int total;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notice_comment);
        ButterKnife.bind(this);
        getBase();
        setTitleLeftBtn();
        setTitleName(R.string.notice_comment_name);
        setTitleRightBtn(R.string.notice_empty, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clearMsg();
            }
        });
        initView();
        getData();

        int num = ForPreference.getInt(ForContents.APP_NOTICE_MSG) - 1;
        ForPreference.putInt(ForContents.APP_NOTICE_MSG , num);
    }

    private void initView() {
        multiStateView.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.button_error_refish)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiStateView.setViewState(MultiStateView.VIEW_STATE_LOADING);
                        getData();
                    }
                });
        ptrlDownRefreshFrameLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, pullToRefreshListView.getRefreshableView(), header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pageIndex = 1;
                getData();
            }
        });
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            //下拉刷新数据
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
            }

            //上拉加载更多
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if(lists.size()<total){
                    getData();
                }else{
                    ForToast.showToast("没有更多了");
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            pullToRefreshListView.onRefreshComplete();
                        }
                    },300);
                }
            }
        });
        pullToRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                System.out.println("i:" + i);
                Intent intent = new Intent(Notice_CommentActivity.this, CircleDetailsActivity.class);
                intent.putExtra("fcid", ((NoticeCommentBean.DataBean) adapter.getItem(i - 1)).getFcid());
                startActivity(intent);
            }
        });
    }

    private void getData() {
        System.out.println("上拉加载:"+pageIndex);
        Map<String, String> formMap = new HashMap<>();
        formMap.put("pageindex", pageIndex + "");
        formMap.put("pagesize", pageSize + "");
        formMap.put("usercode", ForPreference.getString(ForContents.USER_CODE));
        ForHttp.setMsg(HttpApi.ROOT_PATH + "api/Message/GetCommentsMessage", formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                if(pullToRefreshListView.isRefreshing()){
                    pullToRefreshListView.onRefreshComplete();
                }
                if (ptrlDownRefreshFrameLayout.isRefreshing()) {
                    ptrlDownRefreshFrameLayout.refreshComplete();
                }
                if (pageIndex == 1) {
                    multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                } else {
                    ForToast.showToast("网络无连接");
                }
            }

            @Override
            public void onResponse(String response) {
                System.out.println("评论:" + response);
                if(pullToRefreshListView.isRefreshing()){
                    pullToRefreshListView.onRefreshComplete();
                }
                if (ptrlDownRefreshFrameLayout.isRefreshing()) {
                    ptrlDownRefreshFrameLayout.refreshComplete();
                }
                NoticeCommentBean bean = new Gson().fromJson(response, NoticeCommentBean.class);
                if (bean.getStatus() == 200) {
                    List<NoticeCommentBean.DataBean> list = bean.getData();
                    if (list != null && list.size() > 0) {
                        total = bean.getTotal();
                        if (pageIndex == 1) {
                            lists.clear();
                        }
                        lists.addAll(list);
                        pageIndex++;
                        multiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        if (adapter != null) {
                            adapter.notifyDataSetChanged();
                        } else {
                            adapter = new NoticeCommentAdapter(Notice_CommentActivity.this, lists);
                            pullToRefreshListView.setAdapter(adapter);
                        }
                    } else {
                        if (pageIndex == 1) {
                            multiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                        } else {
                            ForToast.showToast("没有更多了");
                        }
                    }
                } else {
                    multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                }
            }
        });
    }

    private void clearMsg() {
        Map<String, String> formMap = new HashMap<>();
        formMap.put("type", "1");
        formMap.put("pageindex", pageIndex + "");
        formMap.put("pagesize", pageSize + "");
        formMap.put("usercode", ForPreference.getString(ForContents.USER_CODE));
        ForHttp.setMsg(HttpApi.ROOT_PATH + "/api/Message/GetCleanMessage", formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForToast.showToast("网络无连接");
            }

            @Override
            public void onResponse(String response) {
                System.out.println("清空评论："+response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        ForToast.showToast("成功清空");
                        adapter.clear();
                        multiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
